package ciicos.util;

import ciicos.base.entity.DictionaryDataEntity;
import ciicos.base.service.DictionaryDataService;
import ciicos.model.lineline.LineLineListVO;
import ciicos.util.convert.DataDicConvert;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;


@Component
public class DataDicUtil {

    @Autowired
    private DictionaryDataService dictionaryDataService;

    public DataDicConvert getDataDicConvert(String dictionaryTypeId){
        return new DataDicConvert(dictionaryDataService.getList(dictionaryTypeId,false));
    };


    public <T> void replaceCodeWithName(
            List<T> list,
            String dictionaryTypeId,
            Function<T, String> codeGetter,  // 函数：T -> 编码（如 user -> user.getDeptCode()）
            BiConsumer<T, String> nameSetter // 函数：(T, 名称) -> 设置名称（如 (user, name) -> user.setDeptName(name)）
    ) {
        if(ListUtil.isEmpty(list)){
            return ;
        }
        List<DictionaryDataEntity> dictList = dictionaryDataService.getList(dictionaryTypeId,false);
        if(dictList==null){
            dictList = new ArrayList<>();
        }
        // 1. 字典转为 Map<编码, 名称>（提高查询效率）
        Map<String, String> codeToNameMap = dictList.stream()
                .collect(Collectors.toMap(
                        DictionaryDataEntity::getEnCode,
                        DictionaryDataEntity::getFullName,
                        (existing, replacement) -> existing // 编码重复时保留第一个
                ));
        //2.还需要根据id查询
        codeToNameMap.putAll(
                dictList.stream()
                        .collect(Collectors.toMap(
                                DictionaryDataEntity::getId,
                                DictionaryDataEntity::getFullName,
                                (existing, replacement) -> existing // 编码重复时保留第一个
                        ))
        );

        // 2. 遍历列表，替换每个对象的编码为名称
        list.forEach(t -> {
            String code = codeGetter.apply(t); // 通过函数获取编码
            String name = codeToNameMap.getOrDefault(code, code); // 查字典，默认保留原编码
            nameSetter.accept(t, name); // 通过函数设置名称
        });
    }


}
